// $Id: filedistributorinsert.cpp 67 2004-11-09 14:59:24Z hansemil $
#include "filedistributorinsert.h"
#include "networknaive.h"
#include <iostream>
using namespace std;

/**
 * @param insertHTL The Hops To Live to use for the insert calls.
 */
FileDistributorInsert::FileDistributorInsert(list<Node *> *nodes, unsigned int insertHTL)
	: FileDistributor(nodes), m_insertHTL(insertHTL)
{
}

/**
 * Does the acctual distribution of the files.
 */
void FileDistributorInsert::distribute()
{
	unsigned int index = 0;
	File *file;

	// Create a Naive(tm) network for transfering
	Network *network = new NetworkNaive(m_nodes);

	// For all files to distribute
	while ((file = FileHandler::getFileByIndex(index++))) {
		// Find a random node. (Save)
		int nodeIndex = rand()%m_nodes->size();
		list<Node *>::iterator node=m_nodes->begin();
		for (int n=0; n<nodeIndex; n++) {
			node++;
		}
		Node *startNode = (*node);
		assert(startNode);

		// Insert the file
		startNode->insertFile(file, m_insertHTL);

		// Run network
		network->transfer();

		// For all Node in TransferChain...
		Node *currentNode = startNode;
		Node *nextNode = 0;
		while (currentNode) {
			// Get next transfer->node in chain
			Transfer *transfer = currentNode->getTransfer(0);

			// Check if we have more nodes in the transfer chain
			if (transfer) {
				// Schedule to visit next node in transfer chain
				nextNode = (Node *) transfer->m_destination;
			}
			else {
				// We are done after this iteration, nothing more to do
				nextNode = 0;
			}

			// Set request,insert to 0 (and save old values)
			float oldRequest = startNode->getRequestProbability();
			float oldInsert = startNode->getInsertProbability();
			currentNode->setRequestProbability(0.0f);
			currentNode->setInsertProbability(0.0f);

			// Execute (to clean up)
			currentNode->execute();

			// Restore old request and insert values
			currentNode->setRequestProbability(oldRequest);
			currentNode->setInsertProbability(oldInsert);

			// Set current node to next node
			currentNode = nextNode;
		}
	}
}
